package org.jeecg.modules.oa.controller;

import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Lists;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.oa.entity.OaReportPlan;
import org.jeecg.modules.oa.entity.OaReportWeek;
import org.jeecg.modules.oa.service.IOaJournalService;
import org.jeecg.modules.oa.service.IOaReportPlanService;
import org.jeecg.modules.oa.service.IOaReportWeekService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 周报表
 * @Author: jeecg-boot
 * @Date: 2019-09-17
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "周报表")
@RestController
@RequestMapping("/b/oaReportWeek")
public class OaReportWeekController {
    @Autowired
    private IOaReportWeekService reportWeekService;
    @Autowired
    private IOaReportPlanService reportPlanService;
    @Autowired
    private ISysDepartService departService;
    @Value("${web.imageFileUrl}")
    private String imageFileUrl;
    @Autowired
    private ISysUserRoleService sysUserRoleService;

    /**
     * 自定义分页列表查询
     *
     * @param oaReportWeek
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "周报表-分页列表查询")
    @ApiOperation(value = "周报表-分页列表查询", notes = "周报表-分页列表查询")
    @GetMapping(value = "/list2")
    public Result<IPage<OaReportWeek>> queryPageList2(OaReportWeek oaReportWeek,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                      HttpServletRequest req) {
        List<String> departIds = sysUserRoleService.queryDepartIds(oaReportWeek);
        System.out.println(departIds.toString());
        String departStr = "AND o.id in ('')";
        if(departIds.size() > 0){
            departStr = " AND o.id in ('"+String.join("','",departIds)+"')";
        }
        Result<IPage<OaReportWeek>> result = new Result<>();
        Page<OaReportWeek> page = new Page<>(pageNo, pageSize);
        page = reportWeekService.find(page, oaReportWeek,departStr);
        return getResule(page, result);


    }

    /**
     * 当前登录人的周报查询
     *
     * @param oaReportWeek
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "我的工作日志表-分页列表查询")
    @ApiOperation(value = "我的工作日志表-分页列表查询", notes = "我的工作日志表-分页列表查询")
    @GetMapping(value = "/myList")
    public Result<IPage<OaReportWeek>> queryPageMyList(OaReportWeek oaReportWeek,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                       HttpServletRequest req) {
        LoginUser sysUser = SsoUtil.getLoginUser();
        oaReportWeek.setCreateBy(sysUser.getId());
        Result<IPage<OaReportWeek>> result = new Result<IPage<OaReportWeek>>();
        Page<OaReportWeek> page = new Page<OaReportWeek>(pageNo, pageSize);
        page = reportWeekService.find(page, oaReportWeek,"");
        return getResule(page, result);
    }

    /**
     * 按用户名字自定义分页列表查询历史周报
     *
     * @param oaReportWeek
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "工作日志表-分页列表查询")
    @ApiOperation(value = "工作日志表-分页列表查询", notes = "工作日志表-分页列表查询")
    @GetMapping(value = "/byNameList")
    public Result<IPage<OaReportWeek>> byNameListPage(OaReportWeek oaReportWeek,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                      HttpServletRequest req) {
        Result<IPage<OaReportWeek>> result = new Result<IPage<OaReportWeek>>();
        Page<OaReportWeek> page = new Page<OaReportWeek>(pageNo, pageSize);
        page = reportWeekService.findSelfList(page, oaReportWeek);
        return getResule(page, result);
    }


    @RequestMapping(value = "/getThisWeekPlan")
    @ResponseBody
    public Result<List<OaReportPlan>> getThisWeekPlan(HttpServletRequest req) {
        Result<List<OaReportPlan>> result = new Result<List<OaReportPlan>>();
        LoginUser user = SsoUtil.getLoginUser();
        //Date lastWeekDate = DateUtils.addDate(new Date(), -7);
        List<OaReportPlan> lists = reportPlanService.getThisWeekPlan(user.getId(), new Date());
        if (!CollectionUtil.isNotEmpty(lists)) {//如果没有本周计划，则把周报日期传到前端（解决前端将周日作为一周的第一天问题）
            OaReportPlan rp = new OaReportPlan();
            Map<String, Date> weekDate = DateUtils.getWeekDate();
            rp.setWorkDateFrom(weekDate.get("mondayDate"));
            rp.setWorkDateTo(weekDate.get("sundayDate"));
            lists.add(rp);
        }
        result.setResult(lists);
        return result;
    }

    /**
     * 获取当前用户的本周周报
     * @return
     */
    @RequestMapping(value = "/getReportWeek")
    @ResponseBody
    public Result<OaReportWeek> getReportWeek() {
        LoginUser user = SsoUtil.getLoginUser();
        OaReportWeek reportWeek = reportWeekService.findByCreateBYAndNew(user.getId(),new Date());
        if(reportWeek!=null){
            return Result.ok("已添加周报");
        }else{
            return Result.error("暂无本周周报");
        }
    }

    /**
     * 分页列表查询
     *
     * @param oaReportWeek
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "周报表-分页列表查询")
    @ApiOperation(value = "周报表-分页列表查询", notes = "周报表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<OaReportWeek>> queryPageList(OaReportWeek oaReportWeek,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                     HttpServletRequest req) {
        Result<IPage<OaReportWeek>> result = new Result<IPage<OaReportWeek>>();
        QueryWrapper<OaReportWeek> queryWrapper = QueryGenerator.initQueryWrapper(oaReportWeek, req.getParameterMap());
        Page<OaReportWeek> page = new Page<OaReportWeek>(pageNo, pageSize);
        IPage<OaReportWeek> pageList = reportWeekService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param reportWeek
     * @return
     */
    @AutoLog(value = "周报表-添加")
    @ApiOperation(value = "周报表-添加", notes = "周报表-添加")
    @PostMapping(value = "/add")
    public Result<OaReportWeek> add(@RequestBody OaReportWeek reportWeek) {
        if (StringUtils.isEmpty(reportWeek.getId())) {// 防止重复提交周报
            LoginUser sysUser = SsoUtil.getLoginUser();
            OaReportWeek newReportWeek = reportWeekService.findByCreateBYAndNew(sysUser.getId(),new Date());
            if (newReportWeek != null) {
                return Result.error("本周周报已经存在，不允许重复提交！");
            }
            Map<String, Date> weekDate = DateUtils.getWeekDate();//生成本周周一和周末的时间
            Date workDateFrom = weekDate.get("mondayDate");// 开始日期(周一)
            Date workDateTo = weekDate.get("sundayDate");// 结束日期（周日）
            reportWeek.setWorkDateFrom(workDateFrom);
            reportWeek.setWorkDateTo(workDateTo);
            reportWeekService.saveReportWeek(reportWeek);
        }else{
            return Result.error("本周周报已经存在，不允许重复提交！");
        }
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param reportWeek
     * @return
     */
    @AutoLog(value = "周报表-编辑")
    @ApiOperation(value = "周报表-编辑", notes = "周报表-编辑")
    @PutMapping(value = "/edit")
    public Result<OaReportWeek> edit(@RequestBody OaReportWeek reportWeek) {
        Result<OaReportWeek> result = new Result<>();
        LoginUser currentUser = SsoUtil.getLoginUser();//当前用户
        if (currentUser == null) {
            return Result.error("用户不存在,修改失败");
        }
        OaReportWeek oaReportWeekEntity = reportWeekService.getById(reportWeek.getId());
        if (oaReportWeekEntity == null) {
            result.error500("未找到对应实体");
        } else {
            reportWeek.setUpdateBy(currentUser.getId());
            reportWeek.setUpdateTime(new Date());
            reportWeekService.editReportWeek(reportWeek);
            result.success("修改成功!");
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "周报表-通过id删除")
    @ApiOperation(value = "周报表-通过id删除", notes = "周报表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id") String id) {
        try {
            reportWeekService.removeById(id);
        } catch (Exception e) {
            log.error("删除失败{}", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "周报表-批量删除")
    @ApiOperation(value = "周报表-批量删除", notes = "周报表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<OaReportWeek> deleteBatch(@RequestParam(name = "ids") String ids) {
        Result<OaReportWeek> result = new Result<OaReportWeek>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.reportWeekService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "周报表-通过id查询")
    @ApiOperation(value = "周报表-通过id查询", notes = "周报表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<OaReportWeek> queryById(@RequestParam(name = "id") String id) {
        Result<OaReportWeek> result = new Result<OaReportWeek>();
        OaReportWeek oaReportWeek = reportWeekService.getById(id);
        if (oaReportWeek == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(oaReportWeek);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<OaReportWeek> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                OaReportWeek oaReportWeek = JSON.parseObject(deString, OaReportWeek.class);
                queryWrapper = QueryGenerator.initQueryWrapper(oaReportWeek, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<OaReportWeek> pageList = reportWeekService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "周报表列表");
        mv.addObject(NormalExcelConstants.CLASS, OaReportWeek.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("周报表列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<OaReportWeek> listOaReportWeeks = ExcelImportUtil.importExcel(file.getInputStream(), OaReportWeek.class, params);
                reportWeekService.saveBatch(listOaReportWeeks);
                return Result.ok("文件导入成功！数据行数:" + listOaReportWeeks.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

    private Result<IPage<OaReportWeek>> getResule(Page<OaReportWeek> page, Result<IPage<OaReportWeek>> result) {
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            for (OaReportWeek orw : page.getRecords()) {
                if (orw != null) {
                    Map<String,Object> map = new HashMap<>();
                    map.put("departName", orw.getDepartName());
                    map.put("departId", orw.getDepartId());
                    map.put("companyId", orw.getCompanyId());
                    map.put("companyName", orw.getCompanyName());
                    map.put("createBy", orw.getCreateBy());
                    map.put("createName", orw.getCreateName());
                    map.put("userName", orw.getUsername());
                    map.put("positionId", orw.getPositionId());
                    map.put("positionCode", orw.getPositionCode());
                    map.put("positionName", orw.getPositionName());
                    map.put("workDateFrom", orw.getWorkDateFrom());
                    map.put("workDateTo", orw.getWorkDateTo());
                    map.put("createTime", orw.getCreateTime());
                    orw.setMap(map);
                }
            }
        }
        result.setResult(page);
        result.setSuccess(true);
        return result;
    }


}
